from django import forms
from web import models
from .bootstrap import BootStrapFrom
from django.core.exceptions import ValidationError
from web.forms import ColorRadioSelect


# project_list modelform
class ProjectListModelForm(BootStrapFrom, forms.ModelForm):
    bootstrap_fields_exclude = ['color']  # 设置color 字段特定样式

    class Meta:
        model = models.Project
        fields = ['name', 'color', 'desc']
        widgets = {
            # 为字段自定义属性
            'desc': forms.Textarea,
            'color': ColorRadioSelect.ColorRadioSelect(attrs={'class': 'color-radio'})
        }

    # 重写init方法 传入request
    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    # 对 项目名进行判别

    def clean_name(self):
        name = self.cleaned_data.get('name')
        # 如果此用户已创建过此项目则提示错误
        project_obj = models.Project.objects.filter(name=name, creator=self.request.tracer.user).first()
        if project_obj:
            raise ValidationError('该项目已存在，请重新创建')

        # 判断用户所拥有的项目个数额度是否正确

        # 获取 当前已使用的项目额度
        current_project_num = models.Project.objects.filter(creator=self.request.tracer.user).count()
        # 获取该用户所有用的所有额度
        project_num_total = self.request.tracer.price_policy.project_num

        # 如果 当前已使用额度 大于等于该用户所有用的额度 则提示错误
        if current_project_num >= project_num_total:
            raise ValidationError('项目个数以达到上限，请升级套餐后创建')
        return name

